package com.hmall.trade.listener;

import com.hmall.api.pay.PayClient;
import com.hmall.api.pay.dto.PayOrderDTO;
import com.hmall.common.constans.MqConstants;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@RequiredArgsConstructor
public class OrderDelayMessageListener {

    private final IOrderService orderService;
    private final PayClient payClient;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.DELAY_ORDER_QUEUE_NAME, durable = "true"),
            exchange = @Exchange(name = MqConstants.DELAY_EXCHANGE_NAME, delayed = "true", type = "direct"),
            key = MqConstants.DELAY_ORDER_KEY
    ))
    public void listenerOrderDelayMessage(Long orderId) {
        //根据订单id查询订单
        Order order = orderService.getById(orderId);
        //判断订单是否支付
        if (order == null || order.getStatus() != 1) {
            return;
        }
        //查流水状态
        PayOrderDTO payOrderDTO = payClient.queryPayOrderByBizOrderNo(orderId);
        if (payOrderDTO != null && payOrderDTO.getStatus() == 2) {
            //已支付标记为支付状态
            orderService.markOrderPaySuccess(orderId);
        }
        //未支付取消订单
        orderService.cancelOrder(orderId);
    }
}
